package com.ustc.hewei.nettyrpc2_0.netty.client.manager;

import com.ustc.hewei.nettyrpc2_0.common.enumeration.RpcError;
import com.ustc.hewei.nettyrpc2_0.common.exception.RpcException;
import com.ustc.hewei.nettyrpc2_0.common.warp.RpcResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

/**
* @description: 未完成请求的处理类
* @author hewei
* @date 2022/9/9 19:35
* @version 1.0
*/

public class UnprocessedRequest {
    private final Map<String, CompletableFuture<RpcResponse>> unprocessed;
    private static final Logger logger = LoggerFactory.getLogger(UnprocessedRequest.class);

    public UnprocessedRequest() {
        unprocessed = new ConcurrentHashMap<>();
    }

    public void add(String requestId, CompletableFuture<RpcResponse> future) {
        unprocessed.put(requestId, future);
    }

    /*
     * @description: 将传入的response的id对应的CompletableFuture设置成完成，并把response传入
     * @author: hewei
     * @date: 2022/9/9 21:30
     **/
    public void complete(RpcResponse response) {
        CompletableFuture<RpcResponse> future = unprocessed.remove(response.getId());
        if (future == null) {
            logger.error("未知的服务端响应 {}", response);
            return;
        }
        future.complete(response);
    }
}